package com.example.demo.config.mq;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
 
@Configuration
public class ActiveMqConfig {
 
    @Value("${activeMq.topicName}")
    private String topic;

    @Value("${activeMq.queueName}")
    private String queue;
 
    @Value("${spring.activemq.broker-url}")
    private String brokeUrl;
 
    @Value("${spring.activemq.user}")
    private String username;
 
    @Value("${spring.activemq.password}")
    private String password;
 
    /**
     * 发布订阅模式
     * @return
     */
    @Bean
    public Topic topic() {
 
        return new ActiveMQTopic(topic);
    }

    /**
     * 点对点
     * @return
     */
    @Bean
    public Queue queue() {
        return new ActiveMQQueue(queue);
    }

    /**
     * 延时队列  //或者封装生产者
     * @return
     */
    @Bean
    public Queue delayedQueue() {
        // 创建一个延时队列，延时时间为10000毫秒
        return new ActiveMQQueue("delayed.queue?consumer.priority=10&delay=10000");
    }
 
    @Bean
    public ConnectionFactory connectionFactory(){
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
//        connectionFactory.setUseAsyncSend(true);   //开启异步投递模式
        connectionFactory.setBrokerURL(brokeUrl);
        connectionFactory.setUserName(username);
        connectionFactory.setPassword(password);
        return connectionFactory;
    }

//    @Bean
//    public DefaultJmsListenerContainerFactory jmsTopicListenerContainerFactory() {
//        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
//        factory.setConnectionFactory(connectionFactory());
//        factory.setPubSubDomain(true);
//        return factory;
//    }
//
//    @Primary
//    @Bean
//    public DefaultJmsListenerContainerFactory jmsQueueListenerContainerFactory() {
//        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
//        factory.setConnectionFactory(connectionFactory());
//        factory.setPubSubDomain(false);
//        return factory;
//    }

    @Bean("jmsTemplate")
    public JmsTemplate genJmsTemplate(){
        return new JmsTemplate(connectionFactory());

    }

    @Bean("jmsMessagingTemplate")
    public JmsMessagingTemplate jmsMessageTemplate(){
        return new JmsMessagingTemplate(connectionFactory());
    }

}